<template>
    <!-- 设计思路:组件全套 -->
    <div class="bodyer" ref="bodyer">
        <el-scrollbar hight="60vh" ref="scrollbarRef" class="show">
            <div ref="innerRef">

                <div v-for="item in chatdata" :key="item.sendtime" class="messageclass">
                    <div v-if="isme(item.email)" class="chatleft">
                        <div style="margin-right: .6rem;">
                            <img :src="item.avatar" style="height:2.5rem;width: 2.5rem;border-radius: .2rem;">
                        </div>
                        <div>
                            <div style="padding-bottom:.3rem;opacity: .7;padding-left: .5rem;display: flex;">
                                {{item.name}}</div>
                            <!--  -->
                            <div style="padding:.3rem;display: flex;">
                                <div style="background-color:white;border-radius:.2rem;">
                                    <div style="padding:.3rem;display: flex;flex-wrap: wrap;">
                                        {{item.context}}</div>
                                </div>
                            </div>
                        </div>

                    </div>
                    <div v-if="!isme(item.email)" class="chatright">
                        <div>
                            <div
                                style="padding-bottom:.3rem;opacity: .7;padding-right: .5rem;display: flex;justify-content: flex-end;">
                                {{item.name}}</div>
                            <!--  -->
                            <div style="padding:.3rem;display: flex;justify-content:flex-end;">
                                <div style="background-color:white;border-radius:.2rem;">
                                    <div style="padding:.3rem;display: flex;flex-wrap: wrap;">
                                        {{item.context}}</div>
                                </div>
                            </div>
                        </div>
                        <div style="margin-left:.6rem">
                            <img :src="item.avatar" style="width:2.5rem;height:2.5rem;border-radius:.2rem">
                        </div>
                    </div>
                </div>

            </div>
        </el-scrollbar>

    </div>
    <!-- 分割 -->
    <div class="send">

        <div class="comment-login">
            <div style="margin-right:1rem;display: flex;align-items: center;justify-content: center;">
                <img :src="userimgsrc" style="width:2.5rem;height:2.5rem;border-radius:50%;" v-show="true">
            </div>
            <div class="login-input" style="margin-right:2rem">
                <div>昵称：</div>
                <div>
                    <el-input :maxlength="11" v-model="qqnum" placeholder="必填" @change="oo">
                    </el-input>
                </div>
            </div>

            <div class="login-input">
                <div>邮箱：</div>
                <div>
                    <el-input v-model="email" placeholder="必填"></el-input>
                </div>
            </div>
        </div>
        <div class="sendcontext">
            <el-input v-model="commentmsg" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="300"
                :show-word-limit="true">
            </el-input>
        </div>
        <div class="sendbtn">
            <el-button :disabled="cansend" resize="none" @click="sendmsg">发射
            </el-button>
        </div>
    </div>


</template>

<!------------------------------>

<script setup lang="ts">
import usericon from '../assets/svg/user-defaulticon.svg?url'
import axios from 'axios'
const global = getCurrentInstance()

//用户数据
type chat = {
    sendtime: number
    context: string
    email: string,
    name: string,
    avatar: string
}
let chatdata = ref<chat[]>([])
let userimgsrc = ref<string>(usericon)
let qqnum = ref<string>()
let email = ref<string>()
let commentmsg = ref<string>()
let regexqq: RegExp = /^[1-9][0-9]{4,10}$/;
let regexemali: RegExp = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
//拉取用户数据:云端
const oo = () => {
    if (qqnum.value || email.value) {
        if (regexqq.test(qqnum.value as string) || regexemali.test(email.value as string)) {
            if (qqnum.value) {
                //API:拉取QQ信息
                axios.get(`https://tenapi.cn/qqname/?qq=${qqnum.value}`).then((res) => {
                    if (res.data.code != 200) {
                        ElMessage.warning({
                            message: res.data.msg,
                            center: true
                        })
                        return
                    }
                    userimgsrc.value = res.data.imgurl
                    qqnum.value = res.data.name
                    email.value = res.data.mail
                    //这里还不是真正的用户信息,所以先不存locals
                }, () => {
                    ElMessage.warning({
                        message: 'QQ信息获取失败,请重试',
                        center: true
                    })
                })
                return
            }
        }
    }
    ElMessage.warning({
        message: '请输入正确的QQ信息',
        center: true
    })
}
//拉取用户数据:本地
if (localStorage.getItem('email') && localStorage.getItem('username') && localStorage.getItem('imgurl')) {
    qqnum.value = localStorage.getItem('username') as string
    email.value = localStorage.getItem('email') as string
    userimgsrc.value = localStorage.getItem('imgurl') as string
}
const cansend = computed(() => {
    if (!commentmsg.value || !qqnum.value || !email.value) {
        return true
    }
    return false
})

const gethistorydata = () => {
    global?.proxy?.$axios.get('/v1/gettodychat').then((res: any) => {
        if (res.data.status == 200) {
            let datt = (res.data.data.map((item: string) => {
                return JSON.parse(item)
            }) as chat[])?.reverse()
            chatdata.value.push(...datt)
        }
    })
}; gethistorydata()
let isme = (email: string): boolean => {
    if (email == localStorage.getItem('email')) {
        return false
    } else {
        return true
    }
}
let ws = new WebSocket(import.meta.env.VITE_WEBSOCKET)
const sendmsg = () => {
    if (!flag.value) {
        //设置重连
        ws = new WebSocket(import.meta.env.VITE_WEBSOCKET)
    }
    //发送json数据
    ws.send(JSON.stringify({
        auth: localStorage.getItem('token'),
        type: 'normal',
        name: qqnum.value,
        email: email.value,
        avatar: userimgsrc.value,
        sendtime: new Date().getTime(),
        context: commentmsg.value
    }))
    commentmsg.value = ''
}
//Flag:连接成功标志
let flag = ref<boolean>(false)
//出一把原始的ws教学
ws.onopen = () => {
    flag.value = true
}
//最重要的消息处理函数
ws.onmessage = (e) => {
    let data = JSON.parse(e.data)
    //类型处理
    if (data.type) {
        if (data.type == 'uptoken') {
            localStorage.setItem('token', data.context)
            localStorage.setItem('username', qqnum.value as string)
            localStorage.setItem('email', email.value as string)
            localStorage.setItem('imgurl', userimgsrc.value)
        } else if (data.type == 'error') {
            ElMessage.warning({
                message: data.context,
                center: true
            })
        }
        //消息接收
    } else if (data.email) {
        chatdata.value.push(data)
    }
}
//在结束前执行close函数
onBeforeUnmount(() => {
    console.log('1111')
    ws.send(JSON.stringify({
        auth: localStorage.getItem('token'),
        type: 'close',
        name: qqnum.value,
        email: email.value,
        avatar: userimgsrc.value,
        sendtime: new Date().getTime(),
        context: ""
    }))
})
//Flag:置底渲染
let scrollbarRef = ref()
let innerRef = ref()
let bodyer = ref()

//解决数据异步操作导致数据没有渲染完获取到实际高度
const renderHight = async () => {
    await nextTick()
    //在nextTick()后能获取到数据?
    if ((innerRef.value!.clientHeight as number) > (bodyer.value!.clientHeight as number) + 32) {
        scrollbarRef.value!.setScrollTop((innerRef.value!.clientHeight as number) - (bodyer.value!.clientHeight as number) + 32)
    }
};
//监听数据变化,数据一旦发生变化就执行函数
watch(() => { return chatdata }, () => {
    renderHight()
}, { deep: true })
</script>

<!------------------------------>

<style scoped lang="scss">
.me {
    justify-content: flex-end;
}

.bodyer {
    background-color: rgb(245, 246, 247);
}

.show {
    padding: 1rem;
    height: 60vh;
    width: 50rem;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .messageclass {
        padding: .5rem;


        .chatleft {
            display: flex;
            padding-top: .2rem;

        }

        .chatright {
            padding-top: .2rem;
            display: flex;
            justify-content: flex-end;
        }
    }
}


.send {
    padding: 2rem;
    height: calc(40vh - 3.75rem);
    background-color: rgb(245, 246, 247);

    .sendinfo {
        display: flex;
        justify-content: space-around;
        align-items: center;
    }
}

.comment-login {
    max-width: 45rem;
    margin: 0 auto;
    border-top: 1px solid rgba(0, 0, 0, .2);
    padding-top: 1.2rem;
    display: flex;
    justify-content: center;

    .login-input {
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

.sendcontext {
    margin: 0 auto;
    max-width: 45rem;
    padding-top: 1.4rem;
}

.sendbtn {
    padding-top: .4rem;
    max-width: 45rem;
    margin: 0 auto;
    display: flex;
    justify-content: flex-end;
}

:deep(.sendcontext textarea) {
    background-color: rgb(245, 246, 247);
}
</style>